<?php

class MailModel extends DbModel {

    protected $_name = 'mail';

    /**
     * Отправка писем с сайта
     *
     * @param string|array $to Recipients
     * @param string $subject Mail subject
     * @param string $body Mail body
     * @return bool
     */
    public function sendMail($to, $subject, $body, $html = true) {
        $config = Zend_Registry::get('config');
        if (isset($config->smtp_server)) {
            $mailConf = array('auth' => 'login', 'username' => $config->smtp_login, 'password' => $config->smtp_password);
            if ($config->smtp_ssl == 'tls' || $config->smtp_ssl == 'ssl') {
                $mailConf['ssl'] = $config->smtp_ssl;
                $mailConf['port'] = $config->smtp_port;
            }
            $transport = new Zend_Mail_Transport_Smtp($config->smtp_server, $mailConf);
            $mail = new Zend_Mail('UTF-8');
            if ($html) {
                $mail->setBodyHtml($body);
            } else {
                $mail->setBodyText($body);
            }
            $mail->setFrom($config->smtp_email, $config->smtp_name);
            $mail->addTo($to);
            $mail->setSubject($subject);
            try {
                $mail->send($transport);
            } catch (Exception $e) {
                $errors[] = 'Unable send mail to ' . $to;
            }
            if (isset($errors) && in_array(true, $errors)) {
                throw new Exception(join('<br />,', $errors));
            }
            return true;
        } else {
            return false;
        }
    }

    public function getTemplates($name = '') {

        if ($name <> '') {
            $res = $this->_db->fetchPairs($this->select()->from(PREFIX . $this->_name, array('name', 'template'))->where('name = ?', $name));
        } else {
            $res = $this->_db->fetchPairs($this->select()->from(PREFIX . $this->_name, array('name', 'template')));
        }
        return $res;
    }

    public function updateTemplates($array) {
        foreach ($array as $key => $value) {
            $this->delete("name = '" . $key . "'");
            $this->insert(array('name' => $key, 'template' => $value));
        }
    }

}